﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Script.UI;
using Script.UI.Panel;
using LitJson;
using MTUnity.Utils;
using Script.Data;
using UnityEngine.Serialization;

public class UI_MainWnd : UIBase
{
    public UI_Warehouse Warehouse;
    public UI_WPanel WareInfoPanel;
    public UI_SPanel SpanelWnd;
    public UI_Overview OverviewWnd;
    public UI_LocationSelect Panel_LocationSelect;
    public UI_HomePanel HomeWnd;
    public GameObject mask;

    public GameObject Overview2Wnd;
    
    //
    private FWarehouse m_Data;

    public int isChangeFlag = 0;
    public GameObject cur;
    public ELocationType curType;
    public int locationId = -1;
    
    public List<GameObject> showObj = new List<GameObject>();
    public static UI_MainWnd Ins;

    protected override void OnAwake()
    {
        Ins = this;
    }

    // Start is called before the first frame update
    void Start()
    {
        //ui
        GlobalEvent.AddEvent(EventName.LocationSelect, OnLocationSelect);
        //data
        

        //data
        m_Data = FWarehouse.GenerateTestData();
        Warehouse.SetWarehouse(m_Data);


        //overview is default
        OverviewWnd.gameObject.SetActive(true);
        Warehouse.gameObject.SetActive(true);
        WareInfoPanel.gameObject.SetActive(true);
        SpanelWnd.gameObject.SetActive(true);

        WareInfoPanel.gameObject.SetActive(false);
        Overview2Wnd.gameObject.SetActive(false);
        SpanelWnd.gameObject.SetActive(false);
        Warehouse.gameObject.SetActive(false);
        SetCurrentLocation(10);

        Warehouse.SetWarehouse(m_Data);
    }

    public void SetCurrentLocation(int iLocationID)
    {
        tick = maxTick;
        locationId = iLocationID;
        CameraController.Ins.OnRecvClickLocationEvent(iLocationID);
        if (LocationAnimatorCtrl.Ins != null)
        {
            LocationAnimatorCtrl.Ins.gameObject.SetActive(false);
        }
        
        var old = cur;
        var hideList = new List<GameObject>(showObj);
        showObj.Clear();
        try
        {
            FLocation location = m_Data.GetLocationWithID(iLocationID);
            // if (location.LocationType == curType)
            // {
            //     return;
            // }
            curType = location.LocationType;
            switch (location.BigLocationType)
            {
                case ELocationType.E_Exterior:
                    {
                        showObj.Add(HomeWnd.gameObject);
                        showObj.Add(OverviewWnd.gameObject);
                        OverviewWnd.SetData(location);

                    }
                    break;
                case ELocationType.E_None:
                    break;
                case ELocationType.E_Interior:
                    {
                        showObj.Add(Overview2Wnd.gameObject);
                        showObj.Add(Panel_LocationSelect.gameObject);
                        showObj.Add(Warehouse.gameObject);
                        // OverviewWnd.SetData(location);
                        Warehouse.SetLocation(location.ID);
                    }
                    break;
                case ELocationType.E_Enter:
                case ELocationType.E_Exit:
                case ELocationType.E_EnterOrExit:
                    {
                        cur =  WareInfoPanel.gameObject;
                        showObj.Add(WareInfoPanel.gameObject);
                        showObj.Add(Warehouse.gameObject);
                        hideList.Add(Panel_LocationSelect.gameObject);
                        WareInfoPanel.SetData(location);
                        Warehouse.SetLocation(location.ID);
                    }
                    break;
                case ELocationType.E_NormalSorting:
                case ELocationType.E_UnNormalSorting:
                case ELocationType.E_SortingLine:
                    {
                        cur =  SpanelWnd.gameObject;
                        showObj.Add(SpanelWnd.gameObject);
                        hideList.Add(Panel_LocationSelect.gameObject);
                        showObj.Add(Warehouse.gameObject);
                        Warehouse.SetLocation(location.ID);
                        SpanelWnd.SetData(location);
                    }
                    break;
                default:
                    break;
            }
        }
        catch (Exception e)
        {
            Debug.LogError(e);
        }

        foreach (var hide in hideList)
        {
            if(showObj.IndexOf(hide) != -1)
            {
                StartCoroutine(PlayChange(hide, hide, iLocationID));
            }
            else
            {
                StartCoroutine(PlayChange(hide, null, iLocationID));
            }
        }
        foreach (var show in showObj)
        {
            if(hideList.IndexOf(show) == -1)
            {
                StartCoroutine(PlayChange(null, show, iLocationID));
            }
        }
        
    }

    public float GetAnimationLength(Animator animator, string name)
    {
        var clips = animator.runtimeAnimatorController.animationClips;
        foreach (var animationClip in clips)
        {
            if (name == animationClip.name || animationClip.name.Contains(name))
            {
                return animationClip.length;
            }
        }

        return 0;
    }

    public IEnumerator PlayChange(GameObject hide, GameObject show, int iLocationID)
    {
        // if (hide == show)
        // {
        //     yield break;
        // }
        isChangeFlag++;
        mask.SetActive(isChangeFlag != 0);
        if (hide != null && hide.activeSelf)
        {
            var animtor = hide.GetComponent<Animator>();
            if (animtor)
            {
                animtor.Play("close");
                yield return new WaitForSeconds(GetAnimationLength(animtor, "close"));
                hide.SetActive(false);
            }
            else
            {
                hide.SetActive(false);
            }
        }

        if (show != null)
        {
            show.SetActive(true);
            var animtor = show.GetComponent<Animator>();
            if (animtor)
            {
                animtor.Play("open");
                yield return new WaitForSeconds(GetAnimationLength(animtor, "open"));
            }
            else
            {
                show.SetActive(true);
            }
        }
        mask.SetActive(isChangeFlag == 0);
        isChangeFlag--;
        if (isChangeFlag == 0 && LocationAnimatorCtrl.Ins != null)
        {
            LocationAnimatorCtrl.Ins.gameObject.SetActive(true);
            LocationAnimatorCtrl.Ins.OnChange(iLocationID);
        }
    }
    
    void OnLocationSelect(object param)
    {
        if (isChangeFlag > 0)
        {
            return;
        }
        Event_LocationSelect evt = (Event_LocationSelect) param;
        Debug.Log(evt.LocationID);
        SetCurrentLocation(evt.LocationID); 
    }

    public class TipsInfo
    {
        public MTJSONObject tipsData;
        public PositionConf conf;
    }
    
    public Dictionary<int,List<string>> THWarningInfo = new Dictionary<int,List<string>>();
    public Dictionary<int,List<TipsInfo>> sortLineWaringInfoList = new Dictionary<int,List<TipsInfo>>();
    private int index;
    private float tick;
    public float maxTick = 25;
    public void PushWaringInfo(int id,MTJSONObject jsonData, PositionConf conf)
    {
        var info = new TipsInfo();
        if (!sortLineWaringInfoList.ContainsKey(id))
        {
            sortLineWaringInfoList.Add(id, new List<TipsInfo>());
        }
        sortLineWaringInfoList[id].Add(info);
        tick = maxTick;
    }

    public void PushWaringInfo(int id, string content)
    {
        if (!THWarningInfo.ContainsKey(id))
        {
            THWarningInfo.Add(id, new List<string>());
            return;
        }

        if (THWarningInfo[id].Contains(content))
        {
            return;
        }
        THWarningInfo[id].Add(content);
        tick = maxTick;
    }
    
    public void ClearWaringInfo()
    {
        sortLineWaringInfoList.Clear();
        tick = maxTick;
    }

    public void ClearTHrWaringInfo()
    {
        THWarningInfo.Clear();
        tick = maxTick;
    }

    public void Update()
    {
        UpdateTips();
    }

    public void UpdateTips()
    {
        if (locationId == -1)
        {
            return;
        }

        if (!sortLineWaringInfoList.ContainsKey(locationId))
        {
            sortLineWaringInfoList.Add(locationId, new List<TipsInfo>());
        }

        if (!THWarningInfo.ContainsKey(locationId))
        {
            THWarningInfo.Add(locationId, new List<string>());
        }
        
        if (sortLineWaringInfoList[locationId].Count <= 0 && THWarningInfo[locationId].Count <= 0)
        {
            TipsWnd.Ins.gameObject.SetActive(false);
            index = 0;
            tick = 0;
            return;
        }
        tick += Time.deltaTime;
        if (tick >= maxTick)
        {
            TipsWnd.Ins.gameObject.SetActive(false);
            TipsWnd.Ins.gameObject.SetActive(true);
            tick = 0;
            index += 1;
            index %= (sortLineWaringInfoList[locationId].Count + THWarningInfo[locationId].Count);
            
            if (index < sortLineWaringInfoList[locationId].Count)
            {
                TipsWnd.Ins.RefreshWithWaringInfo(sortLineWaringInfoList[locationId][index]);
            }
            else
            {
                TipsWnd.Ins.RefreshWithWaringInfo(THWarningInfo[locationId][index - sortLineWaringInfoList[locationId].Count]);
            }
        }

    }
}
